<!-- eslint-disable no-mixed-spaces-and-tabs -->
<template>
  <div class="box">
    <div class="box-right">
      <div class="box-right-title" style="display: flex; flex-direction: row">
        <h2 style="flex: 10">借阅管理</h2>
        <el-button
          type="primary"
          round
          size="small"
          style="flex: 1"
          @click="refresh"
        >
          刷新
        </el-button>
        <div style="flex: 1"></div>
      </div>
      <div class="box-right-main">
        <!-- <div class="top">
          <div class="top-right">
            <el-input v-model="input" placeholder="请输入内容"></el-input>
            <el-input v-model="input" placeholder="请输入内容"></el-input>
          </div>
        </div> -->
        <div class="main">
          <div class="flex-box">
            <h3 style="flex: 2">图书借阅</h3>
            <div style="flex: 3"></div>
            <div class="top-right" style="flex: 4">
              <!-- 一级分类选择器 -->
              <el-select
                v-model="selectedMainCategory"
                value-key="id"
                placeholder="主分类"
                clearable
                style="width: 150px; margin-right: 10px"
                @change="refreshBookTable(selectedMainCategory)"
              >
                <el-option key="-1" label="全部" :value="allBooksCategory" />
                <el-option
                  v-for="category in fullCategories"
                  :key="category.id"
                  :label="category.name"
                  :value="category"
                />
              </el-select>

              <!-- 二级分类选择器 -->
              <el-select
                v-model="selectedSubCategory"
                value-key="id"
                placeholder="子分类"
                :disabled="!selectedCategory"
                style="width: 150px"
                @change="refreshBookTable(selectedSubCategory)"
              >
                <el-option
                  v-for="sub in selectedMainCategory?.children || []"
                  :key="sub.id"
                  :label="sub.name"
                  :value="sub"
                />
              </el-select>
            </div>
            <el-input
              placeholder="全字段搜索……"
              style="flex: 2"
              v-model="bookSearch"
            ></el-input>
          </div>
          <br />
          <el-table :data="booksForTable" height="280">
			<el-table-column prop="coverUrl" label="封面" width="90">
              <template #default="{ row }">
                <img
                  v-if="row.coverUrl"
                  :src="row.coverUrl.startsWith('http')? row.coverUrl : getServerFileURL(`/user/${row.id}/avatar`)"
                  style="width: 60px; height: 80px; object-fit: cover"
                />
                <div v-else style="width: 60px; height: 80px; text-align: center; line-height: 80px;">
					无图片
				</div>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="书名" width="200">
            </el-table-column>
            <el-table-column prop="author" label="作者" width="">
            </el-table-column>
            <el-table-column prop="category" label="分类" width="">
            </el-table-column>
            <el-table-column prop="isbn" label="ISBN" width="200">
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="">
            </el-table-column>
            <el-table-column prop="" label="操作" width="">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  round
                  size="small"
                  @click="borrow(scope.row.id)"
                >
                  借阅
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main">
          <div class="flex-box">
            <h3 style="flex: 1">借阅记录</h3>
            <div style="flex: 6"></div>
            <el-select
              style="flex: 2"
              v-model="borrowRecordsfilterCode"
              placeholder="请选择"
              @change="filterBorrowRecordsForTable"
            >
              <el-option label="全部" value="0" />
              <el-option label="未归书" value="1" />
              <el-option label="已还书" value="2" />
            </el-select>
            <div style="flex: 0.3"></div>
            <el-input
              placeholder="全字段搜索……"
              style="flex: 3"
              v-model="borrowRecordSearch"
            ></el-input>
          </div>
          <br />
          <!-- <div id="barChart" style="width: 100%; height: 340px"></div> -->
          <el-table :data="borrowRecordsForTable" height="280">
            <el-table-column prop="user" label="用户" width="150">
            </el-table-column>
            <el-table-column prop="book" label="图书" width="200">
            </el-table-column>
            <el-table-column prop="borrowTime" label="借书时间">
            </el-table-column>
            <el-table-column prop="returnTime" label="还书时间">
              <template slot-scope="scope">
                <el-button
                  v-if="
                    scope.row.returnTime == null &&
                    (scope.row.userId == currentUserId || isAdmin)
                  "
                  type="primary"
                  round
                  size="small"
                  @click="returnBook(scope.row.id)"
                >
                  还书
                </el-button>
                <span v-else>{{ scope.row.returnTime }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="overdueDays" label="逾期天数" width="100">
            </el-table-column>
            <el-table-column prop="overdueFine" label="逾期费用" width="100">
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script src="../js/echarts.min.js"></script>
<script>
import {
  getFullCategories,
  getCategoriesAndBooks,
  getAllBorrowRecords,
  operation,
} from "@/Service/borrowing-management.js";
import { getAllUsers } from "@/Service/user-managament.js";
import { loginUtil } from "@/Service/login.js";
import {getServerFileURL} from '@/util/request.js'
export default {
  data() {
    return {
      currentUserId: loginUtil.getCurrentUserId(),
      isAdmin: false,
      users: [],

      fullCategories: [],
      books: [],
      booksForTable: [],
      allBooksCategory: { books: this.books },
      selectedCategory: null,
      selectedMainCategory: null,
      selectedSubCategory: null,
      bookSearch: "",
      booksFilter: (item) => true,

      borrowRecords: [],
      borrowRecordsForTable: [],
      borrowRecordSearch: "",
      borrowRecordsfilterName: "全部",
      borrowRecordsFilter: (item) => true,
      borrowRecordsfilterCode: "",
    };
  },
  async mounted() {
    this.isAdmin = await loginUtil.isAdmin();
    await this.refresh();
  },
  methods: {
    async refresh() {
      this.users = (await getAllUsers()).data;

      this.fullCategories = await getFullCategories();
      this.loadFullCategories();
      const { categories, books } = getCategoriesAndBooks(this.fullCategories);
      this.categories = categories;
      this.books = books;
      this.refreshBookTable();

      const res = await getAllBorrowRecords();
      if (res.code != 200) {
        this.$message.error(res.message);
        return;
      }
      this.borrowRecords = res.data;
      this.refreshBorrowTable();
    },
    async borrow(bookId) {
      const res = await operation.borrowBookById(bookId);
      if (res.code != 200) {
        this.$message.error(res.message);
        return;
      }
      this.$message.success("借阅成功！");
      await this.refresh();
    },
    async returnBook(borrowId) {
      const res = await operation.returnBookByUserBookId(borrowId);
      if (res.code != 200) {
        this.$message.error(res.message);
        return;
      }
      this.$message.success("还书成功！");
      this.refresh();
    },
    loadFullCategories() {
      function assignCategoryWithFullBooks(category) {
        if (!Array.isArray(category?.children)) return [];
        category.children.forEach((subcategory) => {
          category.books = [
            ...category.books,
            ...assignCategoryWithFullBooks(subcategory),
          ];
        });
        return category.books;
      }
      this.fullCategories.forEach((category) =>
        assignCategoryWithFullBooks(category)
      );
    },
    refreshBookTable(category) {
      if (category) {
        this.selectedCategory = category;
      }
      if (category == this.selectedMainCategory) {
        this.selectedSubCategory = null;
      }
      if (this.selectedCategory) {
        this.selectedCategory = this.categories.find(
          (c) => c.id == this.selectedCategory.id
        );
      }
      this.booksForTable = this.selectedCategory?.books || this.books;
      this.booksForTable = this.booksForTable
        .filter((book) => {
          for (let key in book) {
            if (String(book[key]).includes(this.bookSearch.trim())) return true;
          }
          return false;
        })
        .map((book) => {
          book.category = this.categories.find(
            (category) => category.id == book.categoryId
          ).name;
          return book;
        });
    },
    refreshBorrowTable() {
      this.borrowRecordsForTable = this.borrowRecords;
      if (!this.isAdmin) {
        this.borrowRecordsForTable = this.borrowRecordsForTable.filter(
          (borrowRecord) => {
            return borrowRecord.userId == this.currentUserId;
          }
        );
      }
      this.borrowRecordsForTable = this.borrowRecordsForTable
        .map((borrowRecord) => {
          borrowRecord.user = this.users.find(
            (user) => user.id == borrowRecord.userId
          ).username;
          borrowRecord.book = this.books.find(
            (book) => book.id == borrowRecord.bookId
          ).title;
          return borrowRecord;
        })
        .filter((borrowRecord) => {
          for (let key in borrowRecord) {
            if (
              String(borrowRecord[key]).includes(this.borrowRecordSearch.trim())
            )
              return true;
          }
          return false;
        })
        .filter(this.borrowRecordsFilter);
    },
    filterBorrowRecordsForTable(value) {
      switch (value) {
        case "0":
          this.borrowRecordsfilterName = "全部";
          this.borrowRecordsFilter = (borrowRecord) => true;
          break;
        case "1":
          this.borrowRecordsfilterName = "未还书";
          this.borrowRecordsFilter = (borrowRecord) => !borrowRecord.returnTime;
          break;
        case "2":
          this.borrowRecordsfilterName = "已还书";
          this.borrowRecordsFilter = (borrowRecord) => borrowRecord.returnTime;
          break;
      }
      this.refreshBorrowTable();
    },
  },
  watch: {
    bookSearch() {
      this.refreshBookTable();
    },
    borrowRecordSearch() {
      this.refreshBorrowTable();
    },
  },
};
</script>
<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: #f0f2f5;
  font-family: "Segoe UI", "Microsoft Yahei", sans-serif;
  color: #333;
}

.box {
  display: flex;
  min-height: 100vh;
  width: 1300px;
  background: linear-gradient(to right, #f8f9fa 0%, #e9ecef 100%);
  margin-left: 90px;
}
.box-left {
  width: 220px;
  background-color: #2c3e50;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: fixed;
  height: 100%;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.box-left:hover {
  background-color: #34495e;
}

.box-left h1 {
  font-size: 24px;
  margin: 30px 0 20px;
  text-align: center;
  letter-spacing: 1px;
}

.box-left aside {
  flex: 1;
  width: 100%;
}

.box-left ul {
  list-style-type: none;
  padding: 0;
}

.box-left li {
  padding: 18px 0;
  text-align: center;
  transition: all 0.3s ease;
}

.box-left a {
  color: #ffffffcc;
  text-decoration: none;
  display: block;
  padding: 10px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
  border-left: 4px solid transparent;
}

.box-left a:hover,
.box-left a.router-link-exact-active {
  background-color: #3498db;
  color: #ffffff;
  transform: scale(1.05);
}

.box-right {
  margin-left: 240px;
  width: calc(100% - 240px);
  padding: 24px;
  transition: all 0.3s ease;
  background-color: #f9fafb;
}

.box-right-nav {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.box-right-title {
  margin-bottom: 20px;
}

.box-right-title h2 {
  font-size: 24px;
  color: #333;
}

.box-right-title p {
  color: #666;
  margin-top: 8px;
}

.top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

/* 按钮组样式优化 */
.top-left {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.top-left .el-button {
  margin-right: 10px;
  border-radius: 8px;
  padding: 10px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.top-left .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border-color: #409eff;
  color: #ffffff;
}

.top-left .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 14px rgba(64, 158, 255, 0.4);
}

/* 搜索区域优化 */
.top-right {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.top-right .el-input {
  width: 200px;
  transition: all 0.3s ease;
}

.top-right .el-input__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  padding: 10px 15px;
  transition: all 0.3s ease;
}

.top-right .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

/* 响应式适配 */
@media (max-width: 1024px) {
  .box-left {
    width: 200px;
  }
  .box-right {
    margin-left: 200px;
    padding: 16px;
  }
}
@media (max-width: 768px) {
  .box {
    flex-direction: column;
  }
  .box-left {
    position: relative;
    width: 100%;
    height: auto;
    flex-direction: row;
    overflow-x: auto;
    overflow-y: hidden;
  }
  .box-right {
    margin-left: 0;
    width: 100%;
  }
  .top {
    flex-direction: column;
    align-items: stretch;
  }
}

.main {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
  border: 1px solid #e4e6eb;
  /* min-height: 300px; */
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.flex-box {
  display: flex;
  flex-direction: row;
}
</style>